<template>
  <div class="count-box">
    <button @click="handleSub" class="minus">-</button>
    <input :value="value" @change="handleChange"  class="inp" type="text">
    <button @click="handleAdd" class="add">+</button>
  </div>
</template>

<script>
export default {
props: {
  value: {
    type: Number,
    default: 1
  }
},
methods: {
  handleAdd() {
    this.$emit('input', this.value + 1)
  },
  handleSub() {
   if(this.value <= 1) {
     return
   }
   this.$emit('input', this.value - 1)
  },
  handleChange(e) {
    const val = +e.target.value//转化为数字 1.数字 2.NaN
    // 限制只能输入数字，输入不合法的值,回退成原来的value值
    if(isNaN(val) || val <= 0) {
      e.target.value = this.value
      return
    }
    this.$emit('input', val)
  }
}
}
</script>

<style lang="less" scoped>
.count-box {
  width: 110px;
  display: flex;
  .add, .minus {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #efefef;
  }
  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #efefef;
    text-align: center;
  }
}
</style>